﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace AIC_PN
{
    public partial class FormDanhMucBaoCao : System.Web.UI.Page
    {
        private static int FatherID;
        private PrepareDataForTreeViewDM DataForTreeViewDM = new PrepareDataForTreeViewDM();
        private static int MaDM = 0;
        private static int KyBaoCao = 0;
        private static int IDDM = 0;
        #region Ham chuc nang

        protected void UpdateDanhMuc(int ID, string TenDM, int STT, string DVT, string BoiDen)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                List<SqlParameter> arrParams = new List<SqlParameter>();
                arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, ID));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenDM", SqlDbType.NVarChar, ParameterDirection.Input, TenDM));
                arrParams.Add(SqlHelper.CreateParameterObject("@STT", SqlDbType.VarChar, ParameterDirection.Input, STT));
                arrParams.Add(SqlHelper.CreateParameterObject("@DVT", SqlDbType.NVarChar, ParameterDirection.Input, DVT));
                arrParams.Add(SqlHelper.CreateParameterObject("@BoiDen", SqlDbType.NVarChar, ParameterDirection.Input, BoiDen));
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
                string sql = "UPDATE [tblDanhMucBaoCao] SET [TenDM] = @TenDM,[STT] = @STT,DVT = @DVT, [BoiDen] = @BoiDen" +
                             ",[UpdateDate] = GETDATE(),[UserID] = @UserID WHERE ID = @ID";
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                MyTran.Commit();
                MyCommon.AddMessage(this.Page.Master, "Cập nhật nội dung báo cáo thành công!", MyConst.MessageType.Success);
            }
            catch
            {
                MyTran.Rollback();
                MyCommon.AddMessage(this.Page.Master, "Cập nhật nội dung báo cáo xảy ra lỗi !", MyConst.MessageType.Error);
            }
        }

        protected void ThemMoiDanhMuc(int KyBaoCao, int MaDM, string TenDonVi, int STT, string DVT, string BoiDen, int FatherID, string ParentID, int UserID)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                List<SqlParameter> arrParams = new List<SqlParameter>();
                arrParams.Add(SqlHelper.CreateParameterObject("@MaDM", SqlDbType.Int, ParameterDirection.Input, MaDM));
                arrParams.Add(SqlHelper.CreateParameterObject("@KyBaoCao_ID_DM", SqlDbType.Int, ParameterDirection.Input, KyBaoCao));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenDM", SqlDbType.NVarChar, ParameterDirection.Input, TenDonVi));
                arrParams.Add(SqlHelper.CreateParameterObject("@STT", SqlDbType.VarChar, ParameterDirection.Input, STT));
                arrParams.Add(SqlHelper.CreateParameterObject("@DVT", SqlDbType.NVarChar, ParameterDirection.Input, DVT));
                arrParams.Add(SqlHelper.CreateParameterObject("@BoiDen", SqlDbType.NVarChar, ParameterDirection.Input, BoiDen));
                arrParams.Add(SqlHelper.CreateParameterObject("@FatherID", SqlDbType.Int, ParameterDirection.Input, FatherID));
                arrParams.Add(SqlHelper.CreateParameterObject("@ParentID", SqlDbType.NVarChar, ParameterDirection.Input, ParentID));
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));

                string sql = "INSERT INTO dbo.tblDanhMucBaoCao(" +
                             "KyBaoCao_ID_DM,MaDM,TenDM,STT,DVT,BoiDen,FatherID,ParentID,CreateDate,UpdateDate,UserID) " +
                             "VALUES (@KyBaoCao_ID_DM,@MaDM,@TenDM,@STT,@DVT,@BoiDen,@FatherID,@ParentID,GETDATE(),GETDATE(),@UserID) " +
                             "DECLARE @ParentIDString NVARCHAR(50) " +
                             "SET @ParentIDString = (SELECT ParentID FROM dbo.tblDanhMucBaoCao WHERE ID = @FatherID) " +
                             "UPDATE dbo.tblDanhMucBaoCao SET ParentID = @ParentIDString + CONVERT(VARCHAR(5),IDENT_CURRENT('dbo.tblDanhMucBaoCao')) + ';' " +
                             "WHERE ID = IDENT_CURRENT('dbo.tblDanhMucBaoCao')";
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                MyTran.Commit();
                MyCommon.AddMessage(this.Page.Master, "Thêm mới nội dung báo cáo thành công !", MyConst.MessageType.Success);
            }
            catch
            {
                MyTran.Rollback();
                MyCommon.AddMessage(this.Page.Master, "Thêm mới nội dung báo cáo xảy ra lỗi !", MyConst.MessageType.Error);
            }
        }

        protected void ThemMoiMotDonVi(int KyBaoCao, int MaDM, string TenDonVi, int STT, string DVT, string BoiDen, int UserID)
        {
            SqlTransaction MyTran = SqlHelper.BeginTransaction();
            try
            {
                List<SqlParameter> arrParams = new List<SqlParameter>();
                arrParams.Add(SqlHelper.CreateParameterObject("@MaDM", SqlDbType.Int, ParameterDirection.Input, MaDM));
                arrParams.Add(SqlHelper.CreateParameterObject("@KyBaoCao_ID_DM", SqlDbType.Int, ParameterDirection.Input, KyBaoCao));
                arrParams.Add(SqlHelper.CreateParameterObject("@TenDM", SqlDbType.NVarChar, ParameterDirection.Input, TenDonVi));
                arrParams.Add(SqlHelper.CreateParameterObject("@STT", SqlDbType.VarChar, ParameterDirection.Input, STT));
                arrParams.Add(SqlHelper.CreateParameterObject("@DVT", SqlDbType.NVarChar, ParameterDirection.Input, DVT));
                arrParams.Add(SqlHelper.CreateParameterObject("@BoiDen", SqlDbType.NVarChar, ParameterDirection.Input, BoiDen));
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));

                string sql = "DECLARE @FatherID NVARCHAR(10)" +
                             "SET @FatherID = IDENT_CURRENT('dbo.tblDanhMucBaoCao') + 1" +
                             "INSERT INTO dbo.tblDanhMucBaoCao(" +
                             "KyBaoCao_ID_DM,MaDM,TenDM,STT,DVT,BoiDen,FatherID,ParentID,CreateDate,UpdateDate,UserID) " +
                             "VALUES (@KyBaoCao_ID_DM,@MaDM,@TenDM,@STT,@DVT,@BoiDen,@FatherID,@FatherID+';',GETDATE(),GETDATE(),@UserID) ";
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                MyTran.Commit();
                MyCommon.AddMessage(this.Page.Master, "Thêm mới nội dung báo cáo thành công !", MyConst.MessageType.Success);
            }
            catch
            {
                MyTran.Rollback();
                MyCommon.AddMessage(this.Page.Master, "Thêm mới nội dung báo cáo xảy ra lỗi !", MyConst.MessageType.Error);
            }
        }

        protected DataTable GetChiTietDanhMuc(int IDDonVi)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, IDDonVi));
            return SqlHelper.ExecuteDataTable(CommandType.Text, "Select * from tblDanhMucBaoCao where ID = @ID", arrParams);
        }

        protected DataTable XoaDanhMuc(int IDDonVi)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, IDDonVi));
            return SqlHelper.ExecuteDataTable(CommandType.Text, "DELETE FROM tblDanhMucBaoCao where ID = @ID", arrParams);
        }

        protected void BindDataToTreeView()
        {
            trvDonVi.Nodes.Clear();
            DataForTreeViewDM.PopulateRootLevel(trvDonVi, MaDM);
            trvDonVi.ExpandAll();
        }

        protected void BindDataToDropDown()
        {
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblDanhMuc WHERE MaDM = 'DanhMucTenBaoCao'");
            ddlTenBaoCao.DataSource = dt;
            ddlTenBaoCao.DataTextField = "TenDM";
            ddlTenBaoCao.DataValueField = "ID";
            ddlTenBaoCao.DataBind();
            ddlTenBaoCao.Items.Insert(0, new ListItem("Chọn báo cáo", "0"));

            dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblDanhMuc WHERE MaDM = 'KyBaoCao'");
            ddlKybaocao.DataSource = dt;
            ddlKybaocao.DataTextField = "TenDM";
            ddlKybaocao.DataValueField = "ID";
            ddlKybaocao.DataBind();
            ddlKybaocao.Items.Insert(0, new ListItem("Chọn kỳ báo cáo", "0"));
        }

        /// <summary>
        /// Thủ tục kiểm tra quyền sử dụng của người dùng có được quyền truy cập vào mục này hay không?
        /// </summary>
        private void CheckPermission()
        {
            Dictionary<string, int> Role = MyCommon.CheckPermission("DanhMucBaoCao");
            if (Role == null || Role["Xem"] == 0)
            {
                Response.Redirect("Index.aspx?p=0");
            }
        }
        #endregion Ham chuc nang

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            if (!IsPostBack)
            {
                BindDataToDropDown();
            }
            int UserID = Convert.ToInt32(Session["userid"]);
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("index.aspx");
        }

        protected void trvDonVi_TreeNodePopulate(object sender, TreeNodeEventArgs e)
        {
            DataForTreeViewDM.PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);
        }

        protected void trvDonVi_SelectedNodeChanged(object sender, EventArgs e)
        {
            btnThemMoi.Visible = true;
            IDDM = Convert.ToInt32(trvDonVi.SelectedValue);
            DataTable ThongTinDonVi = GetChiTietDanhMuc(IDDM);
            txtTenDoiTuong.Text = ThongTinDonVi.Rows[0]["TenDM"].ToString();
            txtSTT.Text = ThongTinDonVi.Rows[0]["STT"].ToString();
            txtDVT.Text = ThongTinDonVi.Rows[0]["DVT"].ToString();
            txtBoiDen.Text = ThongTinDonVi.Rows[0]["BoiDen"].ToString();
            FatherID = Convert.ToInt32(ThongTinDonVi.Rows[0]["FatherID"]);

            btnLuu.CommandName = MyConst.Action.Update;
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            try
            {
                int UserID = Convert.ToInt32(Session["userid"]);
                if (btnLuu.CommandName == MyConst.Action.Update)
                {
                    UpdateDanhMuc(IDDM, txtTenDoiTuong.Text, Convert.ToInt32(txtSTT.Text.Equals("") ? "0" : txtSTT.Text), txtDVT.Text, txtBoiDen.Text);
                    BindDataToTreeView();
                }
                else if (btnLuu.CommandName == MyConst.Action.Addnew)
                {

                    ThemMoiDanhMuc(KyBaoCao, MaDM, txtTenDoiTuong.Text, Convert.ToInt32(txtSTT.Text.Equals("") ? "0" : txtSTT.Text), txtDVT.Text, txtBoiDen.Text, FatherID, "", UserID);
                    BindDataToTreeView();
                }
                else if (btnLuu.CommandName == MyConst.Action.AddOnenew)
                {
                    ThemMoiMotDonVi(KyBaoCao, MaDM, txtTenDoiTuong.Text, Convert.ToInt32(txtSTT.Text.Equals("") ? "0" : txtSTT.Text), txtDVT.Text, txtBoiDen.Text, UserID);
                    BindDataToTreeView();
                }
            }
            catch (Exception)
            {
                MyCommon.AddMessage(this.Page.Master, "Có lỗi xảy ra trong quá trình thao tác !", MyConst.MessageType.Error);
            }
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            txtTenDoiTuong.Text = "";
            txtSTT.Text = "";
            txtDVT.Text = "";
            txtBoiDen.Text = "";
        }

        protected void ddlTenBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnThemMoiMot.Visible = true;
            formUpdate.Visible = true;
            MaDM = Convert.ToInt32(ddlTenBaoCao.SelectedValue);
            DataForTreeViewDM.PopulateRootLevel(trvDonVi, MaDM);
            btnLuu.CommandName = MyConst.Action.AddOnenew;
        }

        protected void btnXoa_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode CurentNode = trvDonVi.SelectedNode;
                if (CurentNode.ChildNodes.Count > 0)
                {
                    MyCommon.AddMessage(this.Page.Master, "Không thể xóa nội dung cấp cha !", MyConst.MessageType.Warning);
                }
                else
                {
                    XoaDanhMuc(Convert.ToInt32(CurentNode.Value));
                    MyCommon.AddMessage(this.Page.Master, "Xóa nội dung báo cáo thành công !", MyConst.MessageType.Success);
                    BindDataToTreeView();
                }
            }
            catch (Exception)
            {
                MyCommon.AddMessage(this.Page.Master, "Có lỗi xảy ra trong quá trình thao tác !", MyConst.MessageType.Error);
            }
        }

        protected void btnThemMoi_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = true;
            btnLuu.CommandName = MyConst.Action.Addnew;
            txtTenDoiTuong.Text = "";
            txtSTT.Text = "";
            txtDVT.Text = "";
            txtBoiDen.Text = "";
        }

        protected void btnThemMoiMot_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = true;
            btnLuu.CommandName = MyConst.Action.AddOnenew;
            txtTenDoiTuong.Text = "";
            txtSTT.Text = "";
            txtDVT.Text = "";
            txtBoiDen.Text = "";
        }

        protected void ddlKybaocao_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChonBaoCao.Visible = true;
        }




    }
}
